package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.service.*;
import io.renren.utils.KdnUtils;
import io.renren.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service("sysOrderService")
public class SysOrderServiceImpl extends ServiceImpl<SysOrderDao, SysOrderEntity> implements SysOrderService {

    @Autowired
    SysOrderDao sysOrderDao;

    @Autowired
    MemberDao memberDao;

    @Autowired
    SysProductDao sysProductDao;

    @Autowired
    KdnUtils kdnUtils;

    @Autowired
    SysMerchantDao sysMerchantDao;

    @Autowired
    RyzExtractLogService ryzExtractLogService;

    @Autowired
    MemberBalanceLogService memberBalanceLogService;
    @Autowired
    CoinCertificateAlterationRecordService coinCertificateAlterationRecordService;
    @Autowired
    CompoundRecordService compoundRecordService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysOrderEntity> page = this.page(
                new Query<SysOrderEntity>().getPage(params),
                new QueryWrapper<SysOrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryByRetailOrMerchantId(Map<String, Object> params) {
        Object userid = params.get("userid");
        Object status = params.get("status");
        Object mobile = params.get("mobile");
        Object c1 = params.get("c1");
        Object c2 = params.get("c2");
        Object orderCode = params.get("orderCode");

        IPage<SysOrderEntity> page = new LambdaQueryChainWrapper<>(sysOrderDao)
                .eq(SysOrderEntity::getStoreId, userid)
                .eq(SysOrderEntity::getType, 2).orderByDesc(SysOrderEntity::getCreationTime)
                .and(null!=status,i->i.eq(SysOrderEntity::getState,status))
                .and(null!=orderCode,d->d.eq(SysOrderEntity::getOrderCode,orderCode))
                .and(null!=mobile,s->s.eq(SysOrderEntity::getMobile,mobile))
                .and(null!=c1&&null!=c2,e->e.between(SysOrderEntity::getCreationTime,c1,c2))
                .ne(SysOrderEntity::getState,8)
                .page(new Query<SysOrderEntity>().getPage(params));

        return new PageUtils(page);
    }

    @Override
    public SysOrderEntity queryDetailById(Integer id) {

        SysOrderEntity orderEntity = sysOrderDao.queryDetailById(id);

        return orderEntity;
    }

    @Override
    @Transactional
    public void deliverGoods(Integer orderId, String address) {
        // 1、查询订单对象
        SysOrderEntity orderEntity = sysOrderDao.selectById(orderId);
        // 2、调用快递鸟接口发货
        String result = kdnUtils.orderOnlineByJson(orderEntity);
        // 3、处理响应
        // TODO: 2020/11/16
        // 4、修改订单状态：已发货
        boolean update = new LambdaUpdateChainWrapper<>(sysOrderDao)
                .eq(SysOrderEntity::getOrderId, orderId)
                .set(SysOrderEntity::getState, 6)
                .update();
        if (!update) {
            throw new RRException("更新订单状态失败", 502);
        }
    }

    @Override
    public void retailPurchase(SysOrderEntity sysOrderEntity) {
        int insert = sysOrderDao.insert(sysOrderEntity);
        if (insert <= 0) {
            throw new RRException("门店进货失败", 501);
        }
        // 1、被进货的门店库存减
        // 2、进货门店余额减
        // 3、交易冻结表冻结余额
        // TODO: 2020-11-26
        // 2、添加订单商品
        Integer orderId = sysOrderEntity.getOrderId();
        List<SysProductSkuEntity> products = sysOrderEntity.getProducts();
        sysOrderDao.saveProducts(orderId, products);

    }

    @Override
    public void confirmReceipt(Integer orderId) {
        // 1、门店库存增
        // 1.1、查询订单商品
        // 1.2、对比门店库存
        // 1.2.1、有增加
        // 1.2.2、没有新增
        // 2、订单状态->已完成
        // TODO: 2020-11-26
    }

    @Override
    public List<Shippercode> queryexpressAllApi() {
        return    sysOrderDao.queryexpressAllApi();
    }

    @Override
    public void sendOrder(HashMap<String, String> params) {
        //快递编号
        String expressCode = params.get("expressCode");
        String orderId = params.get("orderId");
        String express = params.get("express");
        //快递名称
        String deliveryName = params.get("deliveryName");
        //快递单号 手动输入
        String expressNumber = params.get("expressNumber");
        SysOrderEntity sysOrderEntity = sysOrderDao.selectById(Integer.parseInt(orderId));
        SysProductSkuEntity productSkuEntity = sysProductDao.selectByIds(orderId);
        Integer storeId = sysOrderEntity.getStoreId();

        sysOrderDao.updateStocks(storeId,productSkuEntity.getAmount(),productSkuEntity.getPid());
        /**
         * '订单状态:1待付款(默认),2已支付/待发货/已成团,3已发货,4买家确认收货/冻结中,5已完成,6已取消',
         */
        if (sysOrderEntity.getState()==1)throw new RRException("该订单未支付",500);
        if (sysOrderEntity.getState()>2)throw new RRException("该订单已发货,请勿重复操作",500);
        sysOrderEntity.setState(3);
        sysOrderEntity.setLogisticCode(expressNumber);
        sysOrderEntity.setCourier(express);
        if (sysOrderDao.updateById(sysOrderEntity)!=1)throw new RRException("发货失败",500);
    }

    @Override
    public void sendOrders(Integer orderId) {
        SysOrderEntity sysOrderEntity = sysOrderDao.selectById(orderId);
        BigDecimal actualMoney = sysOrderEntity.getActualMoney();
        Integer userId = sysOrderEntity.getUserId();
        //根据购买人Id获取用户信息
        MemberEntity memberEntity = memberDao.selectById(userId);


        //根据商户Id获取商户信息
        SysMerchantEntity sysMerchantEntity = sysMerchantDao.selectById(sysOrderEntity.getStoreId());
        //根据商户手机号码获取用户信息
//        MemberEntity memberEntity = memberDao.selectUser(sysMerchantEntity.getMobile());
        if (sysOrderEntity.getType()==2){
            //提货券
            if (sysOrderEntity.getPaymentType()==0){
                RyzExtractLogEntity r = new RyzExtractLogEntity();

                r.setUid(memberEntity.getUserId());
                r.setBeforeMoney(memberEntity.getIntegral());
                r.setMoney(sysOrderEntity.getActualMoney());
                r.setAfterMoney(memberEntity.getIntegral().add(sysOrderEntity.getActualMoney()));
                r.setOrderCode(orderId.toString());
                r.setCreatedTime(new Date());
                r.setTurnInwards(2);
                r.setSUid(sysOrderEntity.getUserId());
                r.setTransferType(13);
                ryzExtractLogService.save(r);
                memberDao.updateInteger(sysOrderEntity.getActualMoney(),sysOrderEntity.getUserId());
            }
            //余额
            if (sysOrderEntity.getPaymentType()==1){
                MemberBalanceLogEntity m = new MemberBalanceLogEntity();
                m.setUserId(memberEntity.getUserId());
                m.setUserName(memberEntity.getUsername());
                m.setWay(14);
                m.setOutUserId(memberEntity.getUserId());
                m.setOutUserName(memberEntity.getUsername());
                m.setMoney(sysOrderEntity.getActualMoney());
                m.setBeforeMoney(memberEntity.getBalance());
                m.setAfterMoney(memberEntity.getBalance().add(sysOrderEntity.getActualMoney()));
                m.setCreateTime(new Date());
                memberBalanceLogService.save(m);
                sysOrderDao.updates(actualMoney,userId);
            }
            //兑换券
            if (sysOrderEntity.getPaymentType()==4){
                CoinCertificateAlterationRecord m = new CoinCertificateAlterationRecord();
                m.setRuid(memberEntity.getUserId());
                m.setBeforeMoney(memberEntity.getCoinCertificate());
                m.setAfterMoney(memberEntity.getCoinCertificate().add(sysOrderEntity.getMoney()));
                m.setMoney(sysOrderEntity.getMoney());
                m.setAlterationTime(new Date());
                m.setOrderId(sysOrderEntity.getOrderId().toString());
                m.setType(3);
                m.setUid(sysOrderEntity.getStoreId());

                coinCertificateAlterationRecordService.save(m);
                sysOrderDao.coinCertificate(actualMoney,userId);
            }
            //复消积分
            if (sysOrderEntity.getPaymentType()==5){
                CompoundRecord m = new CompoundRecord();
                m.setRuid(memberEntity.getUserId());
                m.setMoney(sysOrderEntity.getMoney());
                m.setBeforeMoney(memberEntity.getCompoundMoney());
                m.setAfterMoney(memberEntity.getCompoundMoney().add(sysOrderEntity.getMoney()));
                m.setAlterationTime(new Date());
                m.setOrderId(sysOrderEntity.getOrderId());
                m.setType(3);
                m.setUid(sysOrderEntity.getStoreId());
                compoundRecordService.save(m);
                sysOrderDao. compoundRecord(actualMoney,userId);
            }

        }
        //修改订单状态
        sysOrderDao.updateState(orderId);
    }


}
